/*
 * wangxiaochen only
 */

package com.naivesoft.util;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;

/**
 * A dialog that prompts the user for a String
 */
public class StringPickerDialog extends AlertDialog implements OnClickListener,
		OnKeyListener{
	
	/**
	 * The callback interface used to indicate the user is done filling in
	 * the time (they clicked on the 'Set' button).
	 */
	public interface OnStringSetListener {
		
		/**
		 * @param view The view associated with this listener.
		 * @param text The text that was set.
		 */
		void onStringSet(EditText view, String text);
	}
	
	private static final String TEXT = "text";
	
	private final EditText mEditText;
	private final OnStringSetListener mCallback;
	
	String mInitialText;
	
	/**
	 * @param context Parent.
	 * @param callback How parent is notified.
	 * @param text The initial String.
	 */
	public StringPickerDialog(Context context,
			OnStringSetListener callback,
			String text) {
		super(context);
		mCallback = callback;
		mInitialText = text;
		
		setButton(context.getText(R.string.util_string_set), this);
		setButton2(context.getText(R.string.util_cancel), (OnClickListener) null);
		//setIcon();TODO
		
		LayoutInflater inflater = 
				(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.util_string_picker_dialog, null);
		setView(view);
		mEditText = (EditText) view.findViewById(R.id.stringPicker);
		
		//initialize state
		mEditText.setText(mInitialText);
		mEditText.setOnKeyListener(this);
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		if (mCallback != null) {
			mEditText.clearFocus();
			mCallback.onStringSet(mEditText, mEditText.getText().toString());
		}
		
	}

	@Override
	public boolean onKey(View view, int keyCode, KeyEvent event) {
		//TODO setTitle()
		return false;
	}
	
	@Override
	public Bundle onSaveInstanceState() {
		Bundle state = super.onSaveInstanceState();
		state.putString(TEXT, mEditText.getText().toString());
		return state;
	}
	
	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		String text = savedInstanceState.getString(TEXT);
		mEditText.setText(text);
		setTitle(text);
	}
}
